package org.example.consumer;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageExt;

import java.util.List;

/**
 * 基于RocketMQ的分布式事务消费者
 * <p>
 * 2PC
 */
@Slf4j
public class TransactionConsumer {


    @SneakyThrows
    public static void createTransactionConsumer() {
        DefaultMQPushConsumer transactionConsumer = new DefaultMQPushConsumer("transaction_consumer");
        transactionConsumer.setNamesrvAddr("192.168.31.104:9876");
        // 设置为顺序消费
        transactionConsumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);

        transactionConsumer.subscribe("TopicTransaction", "*");
        transactionConsumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                // 发送perpare消息
                for (MessageExt messageExt : list) {
                    log.info("消息数据：{}", messageExt);
                }
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });


        transactionConsumer.start();

    }
}
